package pt.chukaku.gtgb;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Vector;

import pt.chukaku.gtgb.parsers.AphroheadCom;
import pt.chukaku.gtgb.parsers.BookDepositoryCoUk;
import pt.chukaku.gtgb.parsers.BookDepositoryCom;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ResultActivity extends Activity {
	private BookListAdapter resultsArrayAdapter;
	String isbn = "";

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.results);
		log("onCreate");

//		resultsArrayAdapter = new ArrayAdapter<String>(this, R.layout.text_view);
		resultsArrayAdapter = new BookListAdapter(this);
		ListView resultsListView = (ListView) findViewById(R.id.results);
		resultsListView.setAdapter(resultsArrayAdapter);

//		resultsListView.setOnItemClickListener(new OnItemClickListener() {
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				AlbumData ab = artistDataSet.getAlbums().get(position);
//				Bundle intent_data = new Bundle();
//				intent_data.putString("name", ab.getAlbumName());
//				intent_data.putString("artist", ab.getArtistName());
//
//				Intent intent = new Intent(getApplicationContext(),
//						AlbumActivity.class);
//				intent.putExtras(intent_data);
//				startActivity(intent);
//			}
//		});

		log("After resultsArrayAdapter");

		Intent the_intent_that_gave_life_to_everything = getIntent();
		Bundle intent_data = the_intent_that_gave_life_to_everything
				.getExtras();

		if (intent_data == null) {
			log("Intent_data == null");
			finish();
		}

		isbn = intent_data.getString("isbn");
		log("After getting isbn");

		new Search().execute(isbn, "0");
		new Search().execute(isbn, "1");
		new Search().execute(isbn,"2");
		log("After search()");
	}

	private class Search extends AsyncTask<String, Book, Void> {

		protected Void doInBackground(String... params) {
			log("Search.doInBackground");
			String isbn = params[0];
			int site = new Integer(params[1]);

			switch (site) {
			case 0:
				log("Before Aphrohead");
				AphroheadCom aphrohead = new AphroheadCom(isbn);
				publishProgress(aphrohead.getBook());
				log("After Aphrohead");
				break;
			case 1:
				log("Before BookDepositoryCom");
				BookDepositoryCom bookDepositoryCom = new BookDepositoryCom(
						isbn);
				publishProgress(bookDepositoryCom.getBook());
				log("After BookDepositoryCom");
				break;
			case 2:
				log("Before BookDepositoryCom");
				BookDepositoryCoUk bookDepositoryCoUk = new BookDepositoryCoUk(
						isbn);
				publishProgress(bookDepositoryCoUk.getBook());
				log("After BookDepositoryCoUk");
				break;
			default:
				break;
			}
			return null;
		}

		protected void onProgressUpdate(Book... values) {
			log("antes de adicionar");
			((BookListAdapter)resultsArrayAdapter).add(values[0]);
			log("depois de adicionar");
		}
	}

	private class BookListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		List<Book> books = new Vector<Book>();
		
		public BookListAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            log("BookListAdapter creator");
		}
		
		public void add(Book book) {
			log("BookListAdapter add");
			this.books.add(book);
			notifyDataSetChanged();
		}

		public int getCount() {
			log("BookListAdapter getcount " + books.size());
			return books.size();
		}

		public Object getItem(int position) {
			log("BookListAdapter getItem " + position);
			return position;
		}

		public long getItemId(int position) {
			log("BookListAdapter getItemId " + position);
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			log("BookListAdapter getView");
			
			if (convertView == null) {
                convertView = mInflater.inflate(R.layout.book_view, null);

                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.cover);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            holder.text.setText(books.get(position).getString());
            log(books.get(position).url);
            holder.icon.setImageBitmap(urlToImage(books.get(position).url));

            return convertView;
		}
	}
	
	static class ViewHolder {
		TextView text;
		ImageView icon;
	}

	private Bitmap urlToImage(String imageUrl) {

		URL myFileUrl = null;
		try {
			myFileUrl = new URL(imageUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			log("urlToImage: MalformedURLException");
		}

		InputStream is = null;
		try {
			is = myFileUrl.openStream();
		} catch (IOException e) {
			e.printStackTrace();
			log("urlToImage: IOException");
		} 
		
		return BitmapFactory.decodeStream(is);
	}
	
	private void log(String position) {
		Log.d("GTG", "ResultActivity: " + position);
	}
}
